//
//  SearchViewController.m
//  GiftSay
//
//  Created by QQn1993 on 16/1/8.
//  Copyright © 2016年 liyinkai. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchArtifactViewController.h"
#import "HomeNewModel.h"
#import "LongTableViewCell.h"

#import "Filters.h"

#import "HotWordsCollectionViewCell.h"

@interface SearchViewController ()<UITextFieldDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UISearchBar *searchbar;
@property (nonatomic,strong) UITableView *table;
@property (nonatomic,strong) UICollectionView *collection;
@property (nonatomic,strong) UICollectionView *hotwordscollection;

#pragma mark 下拉动画

@property (nonatomic,strong) Animal *animal;

//判断搜索是否正在输入
@property (nonatomic,assign) NSInteger isEding;

//加载
@property (nonatomic,assign) NSInteger number;
@property (nonatomic,assign) CGFloat contenty;

//滑动的线
@property (nonatomic,strong) UILabel *line;
@property (nonatomic,strong) UILabel *volatileline;
//切换按钮
@property (nonatomic,strong) UIButton *items;
@property (nonatomic,strong) UIButton *post;

@property (nonatomic,strong) NSMutableArray *ItemsArray;
@property (nonatomic,strong) NSMutableArray *PostArray;
@property (nonatomic,strong) NSMutableArray *hot_words;

@end

//限制一次刷新
static int scrolltimes = 0;


@implementation SearchViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [self.table reloadData];
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"NightMode"] == YES) {
        self.navigationController.navigationBar.barTintColor = kNightModeNavigationColor;
        self.hotwordscollection.backgroundColor = kNightModeColor;
        self.collection.backgroundColor = kNightModeColor;
        self.table.backgroundColor = kNightModeColor;
    } else {
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:248 / 255.0 green:78 / 255.0 blue:78 / 255.0 alpha:1];
    }
    [self.hotwordscollection reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.ItemsArray = [NSMutableArray arrayWithCapacity:0];
    self.PostArray = [NSMutableArray arrayWithCapacity:0];
    self.number = 0;
    
    self.searchbar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
    self.searchbar.placeholder = @"快选一份礼物，送给亲爱的Ta吧";
//    self.searchbar.delegate = self;
    self.searchbar.clearsContextBeforeDrawing = YES;
    
    self.navigationItem.titleView = self.searchbar;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeDatasource) name:UITextFieldTextDidChangeNotification object:nil];
    
    self.isEding = 0;
    
    [self createdChangeButton];
    
    [self createdTableview];
    [self createdCollectionview];
    
    [self gethotwords];
    
    [self createdhot_words];
    
    
    //添加动画view
    self.animal = [[Animal alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.animal];
    //添加动画结束的监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(animalStop:) name:@"tag" object:nil];
    
    
    // Do any additional setup after loading the view.
}

#pragma mark 动画结束监听方法
- (void)animalStop:(NSNotification *)object
{
    [self.collection setContentOffset:CGPointMake(0, 0) animated:YES];
    [self.table setContentOffset:CGPointMake(0, 0) animated:YES];
    
    self.animal.frame = CGRectMake(0, 0, 0, 0);
    self.animal.contetsize = CGSizeZero;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return YES;
}

- (void)changeDatasource
{
    NSLog(@"%@",self.searchbar.text);
    self.isEding = 1;
    
    if (self.searchbar.text.length == 0 || self.searchbar.text == nil) {
        
        NSLog(@"kong");
        
        self.line.hidden = YES;
        self.items.hidden = YES;
        self.post.hidden = YES;
        self.volatileline.hidden = YES;
        self.collection.hidden = YES;
        self.table.hidden = YES;
        
        self.hotwordscollection.hidden = NO;
    }
    else{
        self.line.hidden = NO;
        self.items.hidden = NO;
        self.post.hidden = NO;
        self.volatileline.hidden = NO;
        self.collection.hidden = NO;
        self.table.hidden = NO;
        
        self.hotwordscollection.hidden = YES;
        [self reload];
    }
}

#pragma mark 刷新
- (void)reload
{
    NSLog(@"刷新");
    if (self.ItemsArray.count > 0) {
        [self.ItemsArray removeAllObjects];
    }
    
    if (self.PostArray.count > 0) {
        [self.PostArray removeAllObjects];
    }
    
    [self getItemsAndPost];
}

#pragma mark 加载
- (void)addItem
{
    NSLog(@"加载");
    
    self.number += 1;
    [self getItemsAndPost];
}



//创建切换button
- (void)createdChangeButton
{
    self.line = [[UILabel alloc] initWithFrame:CGRectMake(0, kHeight / 15, kWidth / 2, kHeight / 300)];
    self.line.backgroundColor = [UIColor redColor];
    self.line.hidden = YES;
    [self.view addSubview:self.line];
    
    self.items = [UIButton buttonWithType:UIButtonTypeCustom];
    self.items.hidden = YES;
    self.items.frame = CGRectMake(0,0, kWidth / 2, kHeight / 15);
//    items.backgroundColor = [UIColor redColor];
    self.items.backgroundColor = [UIColor whiteColor];
    [self.items setTitle:@"礼物" forState:UIControlStateNormal];
    [self.items setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.items.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.items addTarget:self action:@selector(bringColletionviewToFont) forControlEvents:UIControlEventTouchUpInside];
    
    self.post = [UIButton buttonWithType:UIButtonTypeCustom];
    self.post.hidden = YES;
    self.post.frame = CGRectMake(kWidth / 2, 0, kWidth / 2,kHeight / 15);
    [self.post setTitle:@"攻略" forState:UIControlStateNormal];
    self.post.backgroundColor = [UIColor whiteColor];
    [self.post setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.post.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.post addTarget:self action:@selector(bringTableviewTofont) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.items];
    [self.view addSubview:self.post];
    
    self.volatileline = [[UILabel alloc] initWithFrame:CGRectMake(kWidth / 2 - kHeight / 1200, 0, kHeight / 600, kHeight / 15)];
    self.volatileline.backgroundColor = [UIColor lightGrayColor];
    self.volatileline.hidden = YES;
    [self.view addSubview:self.volatileline];
    
}

- (void)bringColletionviewToFont
{
    [UIView animateWithDuration:0.5 animations:^{
        self.line.frame = CGRectMake(0, kHeight / 15, kWidth / 2, kHeight / 300);
    }];
    
    [self.view bringSubviewToFront:self.collection];
    [self.view bringSubviewToFront:self.animal];
}

- (void)bringTableviewTofont
{
    [UIView animateWithDuration:0.5 animations:^{
        self.line.frame = CGRectMake(kWidth / 2, kHeight / 15, kWidth / 2, kHeight / 300);
    }];
    
    [self.view bringSubviewToFront:self.table];
    [self.view bringSubviewToFront:self.animal];
}

#pragma mark 创建hot_words
- (void)createdhot_words{
    
    self.hot_words = [NSMutableArray arrayWithCapacity:0];
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.sectionInset = UIEdgeInsetsMake(kWidth / 30, kWidth / 15, kWidth / 20, kWidth / 15);
    flow.minimumInteritemSpacing = kWidth / 15;
    flow.minimumLineSpacing = kWidth / 25;
    
    self.hotwordscollection = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flow];
    self.hotwordscollection.backgroundColor = [UIColor whiteColor];
    self.hotwordscollection.delegate = self;
    self.hotwordscollection.dataSource = self;
    
//    self.hotwordscollection.hidden = NO;
    
    [self.hotwordscollection registerClass:[HotWordsCollectionViewCell class] forCellWithReuseIdentifier:@"HotWordsCollectionViewCell"];
    
    [self.view addSubview:self.hotwordscollection];
}

//创建collectionview
- (void)createdCollectionview
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.sectionInset = UIEdgeInsetsMake(kWidth / 50, kWidth / 50, kWidth/50, kWidth/50);
    
    flow.minimumInteritemSpacing = kWidth / 50;
    flow.minimumLineSpacing = kWidth / 50;
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.line.frame.origin.y + kHeight / 150, self.view.size.width, self.view.size.height - 64 - self.line.frame.origin.y + kHeight / 150) collectionViewLayout:flow];
    self.collection.backgroundColor = [UIColor whiteColor];
    
    [self.collection registerClass:[BaseCollectionViewCell class] forCellWithReuseIdentifier:@"BaseCollectionViewCell"];
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.hidden = YES;
    
    [self.view addSubview:self.collection];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([collectionView isEqual:self.collection]) {
        return CGSizeMake(kWidth / 50 * 23, kHeight / 10 * 4);
    }
    else if ([collectionView isEqual:self.hotwordscollection] && indexPath.section == 0){
        CGRect rect = [QQNGetRect string:self.hot_words[indexPath.row] font:25*SCREEN_WIDTH];
        return CGSizeMake(rect.size.width, rect.size.height - 5);
    }
    else{
        return CGSizeMake(kWidth, kHeight / 20);
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    if ([collectionView isEqual:self.collection]) {
        return 1;
    }
    else{
        return 2;
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if ([collectionView isEqual:self.collection]) {
        return  self.ItemsArray.count;
    }
    else if ([collectionView isEqual:self.hotwordscollection] && section == 0){
        return self.hot_words.count;
    }
    
    return 1;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([collectionView isEqual:self.collection]) {
        BaseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BaseCollectionViewCell" forIndexPath:indexPath];
        if (self.ItemsArray.count > indexPath.row) {
            cell.item = self.ItemsArray[indexPath.row];
        }
        return cell;
    }
    
    else if ([collectionView isEqual:self.hotwordscollection] && indexPath.section == 0){
        HotWordsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotWordsCollectionViewCell" forIndexPath:indexPath];
        cell.name = self.hot_words[indexPath.row];
        return cell;
    }
    
    else{
        HotWordsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotWordsCollectionViewCell" forIndexPath:indexPath];
        cell.name = @"使用选礼神器快速挑选礼物";
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([collectionView isEqual:self.collection] && self.ItemsArray.count > indexPath.row) {
        
        Items *item = self.ItemsArray[indexPath.row];
        
        WebViewController *web = [[WebViewController alloc] init];
        web.url = [NSString stringWithFormat:@"%@%@",kItemsInfo,item.ID];
        [self.navigationController pushViewController:web animated:YES];
    }
    
    else if ([collectionView isEqual:self.hotwordscollection] && indexPath.section == 0){
        
        self.searchbar.text = self.hot_words[indexPath.row];
        [self changeDatasource];
    }
    
    else if ([collectionView isEqual:self.hotwordscollection] && indexPath.section == 1){
        
        SearchArtifactViewController *search = [[SearchArtifactViewController alloc] init];
        
        NSString *str = @"http://api.liwushuo.com/v2/search/item_filter";
        
        [LYKNetWorkTool getWithUrl:str parameter:nil httpHeader:nil resposeType:ResponseTypeDATA success:^(id result) {
                
                id any = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
                
                NSDictionary *data = any[@"data"];
                NSArray *filters = data[@"filters"];
            NSMutableArray *temp = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary *dic in filters) {
                    Filters *filters = [[Filters alloc] initWithDasource:dic];
                    NSLog(@"%ld",filters.channel.count);
                    [temp addObject:filters];
                }
                
//                self.filter = self.hotChanal[0];
            search.array = [NSArray arrayWithArray:temp];
                    [self.navigationController pushViewController:search animated:YES];
//                [self.collection reloadData];
//                [self.choseCollection reloadData];
            } fail:^(NSError *error) {
                
            }];
    }
    
}

#pragma mark 创建tableview
- (void)createdTableview
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, self.line.frame.origin.y + kHeight / 150, kWidth, kHeight - 64 - self.line.frame.origin.y - kHeight/150) style:UITableViewStyleGrouped];
//    self.table.backgroundColor = [UIColor cyanColor];
    
    [self.table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    [self.table registerClass:[LongTableViewCell class] forCellReuseIdentifier:@"LongTableViewCell"];
    
    self.table.dataSource = self;
    self.table.delegate = self;
    self.table.hidden = YES;
    
    [self.view addSubview:self.table];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.PostArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"%f",kHeight / 4);
    return kHeight / 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LongTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LongTableViewCell"];
    if (self.PostArray.count > indexPath.row) {
        cell.model = self.PostArray[indexPath.row];
//        NSLog(@"%@     %@",cell.model.url,cell.model.content_url);
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeNewModel *dic = self.PostArray[indexPath.row];
    WebViewController *web = [[WebViewController alloc] init];
    //可拼接的web
//    web.url = [NSString stringWithFormat:@"%@%@",kPostInfo,dic[@"id"]];
//    web.type = @"html";
    
    web.url = [NSString stringWithFormat:@"%@%@",kPostInfo,dic.ids];
    web.type = @"post";
    
    [self.navigationController pushViewController:web animated:YES];
}

#pragma mark 获取数据
- (void)getItemsAndPost
{
    //获取collection数据
    
    NSString *getEndUrl = [kSearchGETEndURL stringByReplacingOccurrencesOfString: [NSString stringWithFormat:@"offset=%ld",(self.number * 20)] withString:@"offset=0"];
    
    NSString *keyWord = [NSString stringWithString:[self.searchbar.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet symbolCharacterSet]]];
    
    NSString *urlcollection = [NSString stringWithFormat:@"%@%@%@",kSearchGetItemsBeginURL,keyWord,getEndUrl];
    
    NSString *urltable = [NSString stringWithFormat:@"%@%@%@",kSearchGetPostBeginURL,keyWord,getEndUrl];
    
#pragma mark 获取collection items
    [LYKNetWorkTool getWithUrl:urlcollection parameter:nil httpHeader:nil resposeType:ResponseTypeDATA success:^(id result) {
       
        id any = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
//        NSLog(@"************%@",any);
        
        NSDictionary *data = any[@"data"];
        NSArray *items = [NSArray arrayWithArray:data[@"items"]];
        
        if (items.count == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"没有商品了" message:@"换个别的吧" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }
        
        for (NSDictionary *datasource in items) {
            
//            NSDictionary *dic = datasource[@"data"];
            Items *item = [[Items alloc] init];
            item.like = [NSString stringWithFormat:@"%@",datasource[@"favorites_count"]];
            item.ID = [NSString stringWithFormat:@"%@",datasource[@"id"]];
            item.cover_icon = datasource[@"cover_image_url"];
            item.title = datasource[@"name"];
            item.price = [NSString stringWithFormat:@"%@",datasource[@"price"]];
            
            [self.ItemsArray addObject:item];
        }
        
        NSLog(@"****%ld",self.ItemsArray.count);
        [self.collection reloadData];
        
//        [self.collection setContentOffset:CGPointMake(0, 0) animated:YES];
        
        //刷新置0
        scrolltimes = 0;
        
    } fail:^(NSError *erro) {
        NSLog(@"%@",erro);
    }];
    
#pragma mark 获取table数据
    [LYKNetWorkTool getWithUrl:urltable parameter:nil httpHeader:nil resposeType:ResponseTypeDATA success:^(id result) {
        
        id any = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
//        NSLog(@"%@",any);
        NSDictionary *data = any[@"data"];
        NSArray *post = [NSArray arrayWithArray:data[@"posts"]];
//        NSLog(@"%ld****",post.count);
        
        if (post.count == 0 ) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"没有攻略了" message:@"换个别的吧" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }
        
        for (NSDictionary *dic in post) {
            
            HomeNewModel *home = [[HomeNewModel alloc] initWithDictionary:dic];
            home.url = [NSString stringWithFormat:@"%@%@",kPostInfo,home.ids];
            
            [self.PostArray addObject:home];
        }
        
        [self.table reloadData];
        
//        [self.table  setContentOffset:CGPointMake(0, 0) animated:YES];
        
        //刷新置0
        scrolltimes = 0;
        
    } fail:^(NSError *erro) {
        
    }];
    
}

//获取标签
- (void)gethotwords
{
    [LYKNetWorkTool getWithUrl:@"http://api.liwushuo.com/v2/search/hot_words" parameter:nil httpHeader:nil resposeType:ResponseTypeDATA success:^(id result) {
        
        id any = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
        NSDictionary *data = any[@"data"];
        
        NSArray *hot_words = [NSArray arrayWithArray:data[@"hot_words"]];
        
        for (NSString *tag in hot_words) {
            [self.hot_words addObject:tag];
        }
        
        [self.hotwordscollection reloadData];
        
        
    } fail:^(NSError *erro) {
        
    }];
}

#pragma mark -- 下拉刷新
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < -60) {
        [scrollView setContentOffset:CGPointMake(0, -60) animated:YES];
    }
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < 0) {
        NSLog(@"下拉刷新");
        
        self.animal.frame = CGRectMake(0, self.line.frame.origin.y + kHeight / 150, self.view.width, 60);
        self.animal.contetsize = CGSizeMake(kWidth, 60);
        
        [self.animal strat];
        
        [self reload];
    }
    
}


#pragma mark 加载

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.contenty = scrollView.contentOffset.y;
    [self.searchbar resignFirstResponder];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y > self.contenty) {
        if (scrollView.contentOffset.y > scrollView.contentSize.height - 700) {
            
            //加载更多数据
            if (scrolltimes == 0) {
                [self addItem];
                scrolltimes = 1;
            }
        }
    }
}

//取消方法
- (void)dismiss
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
